<?php

class Filter_FilterController extends Core_Controller_Action_Standard {

    public function indexAction() {
        //send the smallest last_update_date type first
        $filter_type = Engine_Api::_()->getItemTable('filter_type')->fetchRow(null, 'last_updated_date');
        var_dump($filter_type->type_name);
		
		// update filter type laste_updated_date
		$filter_type->last_updated_date = date('Y-m-d H:i:s');
		// $filter_type->save();
		
        $view = Zend_Registry::get('Zend_View');
        $template = clone($view);
        
		// ignore type that is implemented in next phrase (ugrade later)
		if (in_array($filter_type->type_name, array('road', 'user', 'destination'))) { return; }
		
		// get filter limit setting
		$filter_limit = 100;
		
		// get filters corresponding with type for first time
		$sl_filters = Engine_Api::_()->getItemTable('filter')->select()
					->where('type_id = ?', $filter_type->getIdentity())
					->where('enabled = ?', 1)
					->order('last_updated_date')
					->limit($filter_limit);
		
		$filters = Engine_Api::_()->getItemTable('filter')->fetchAll($sl_filters);
		
		$valueTable = Engine_Api::_()->getDbTable('values', 'filter');
		$criteriaTable = Engine_Api::_()->getDbTable('criteria', 'filter');
		
		foreach ($filters as $filter) { 
			var_dump($filter->getIdentity());
			$filter_owner = $filter->getOwner();
			$filter_values = Engine_Api::_()->getDbTable('values', 'filter')->select()
						->setIntegrityCheck(false)
						->from(array('v' => $valueTable->info('name')))    
						->join(array('c' => $criteriaTable->info('name')), 'v.criteria_id = c.criteria_id')
						->where('v.filter_id = ?', $filter->getIdentity())
						->query()
						->fetchAll();

			$filterValuesArr = array();
			foreach ($filter_values as $filter_value){
				$filterValuesArr[$filter_value['criteria_name']] = $filter_value['value'];
			}
			
			$itemTable = Engine_Api::_()->getItemTable($filter_type->type_name);
			$categoryTable = Engine_Api::_()->getDbTable('categories', $filter_type->type_name);

			if ($filter_type->type_name == 'event') {
				$select = $itemTable->select()
						->from(array('i' => $itemTable->info('name')))    
						->where('i.title like (?)', "%" . $filterValuesArr['keyword'] . "%")
						->orWhere('i.location like (?)', "%" . $filterValuesArr['country'] . "%")
						->orWhere('i.location like (?)', "%" . $filterValuesArr['state'] . "%")
						->orWhere('i.location like (?)', "%" . $filterValuesArr['city'] . "%")
						->orWhere('i.starttime >= ?', $filterValuesArr['start_date'])
						//->orWhere('zipcode')
						->group('i.event_id');
			}

			if($categoryTable){
				$select = $select->setIntegrityCheck(false)
						->join(array('c' => $categoryTable->info('name')), 'i.category_id = c.category_id', array('category_title' => 'c.title'))
						->orWhere('c.title like (?)', "%" . $filterValuesArr['keyword'] . "%");
			}

			$items = $itemTable->fetchAll($select);
			
			$data_filtered = array();

			foreach ($items as $item) {
				// check notify for event
				if ($filter_type->type_name == 'event') {
					 
					// Add notification
					$notify = Engine_Api::_()->getItemTable('activity_notification')->fetchRow(array(
										'user_id = ?' => $filter_owner->getIdentity(),
										'subject_type = ?' => $filter_type->type_name,
										'subject_id = ?' => $item->getIdentity(),
										'type = ?' => 'filter_new_event'
								));
					
					if (!$notify) {
						Engine_Api::_()->getDbtable('notifications', 'activity')
							->addNotification($filter_owner, $item, Engine_Api::_()->user()->getUser($item->user_id), 'filter_new_event');
					}
					
					// get info to send mail one time
					$item_id = $filter_type->type_name.'_id';
					
					$data_filtered['event-'.$item->$item_id] = $item->toArray();
				}
				
				// check notify for road

				// check notify for destination

				// check notify for blog
				if ($type->type_name == 'blog') {
					if ( $criteria_val['keyword'] == $item->title ) {                                
						// send mail & notification 
						// Add notification
						Engine_Api::_()->getDbtable('notifications', 'activity')
							->addNotification($filter_owner, $item, Engine_Api::_()->user()->getUser($item->owner_id), 'filter_new_blog');;

						 // get info to send mail one time
					}
				}
				
				// update filter laste_id
				$filter->last_id = $item->getIdentity();
				// update filter laste_updated_date
				$filter->last_updated_date = date('Y-m-d H:i:s');  
				$filter->save();
			}

			$this->view->filter_type = $template->filter_type = $filter_type->type_name;
			$this->view->title_filter = $template->title_filter = $filter->title;
			$this->view->items_filtered =  $template->items_filtered = $data_filtered;
			$message = $template->render('_mailFilterEvent.tpl');
			$params = array(
				'info' => $message,
				'host' => $_SERVER['HTTP_HOST'],
				'email' => $filter_owner->email,
				'date' => time(),
				'recipient_title' => $filter_owner->getTitle(),
				'recipient_link' => $filter_owner->getHref(),
				'recipient_photo' => $filter_owner->getPhotoUrl('thumb.icon'),
				'queue' => false
			);
			if (empty($data_filtered)) {
				continue;
			}
			var_dump($data_filtered);
			Engine_Api::_()->getApi('mail', 'core')->sendSystem($filter_owner,
						'filter_event', $params);
		}
		
//		exit('Done.');
	}

}